#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#include <visual.h>
#include <unittest.h>
#include <debug.h>


/**
 * DESC: Tests the visual layer
 *
 * IMP: MEDIUM
 */

char *
find_fname( const char *prefix, const char *suffix )
{
  struct stat s;
  unsigned i = 1;
  char *n = NULL;
  do
    {
      if ( n != NULL )
	free( n );

      asprintf( &n, "%s-%05d.%s", prefix, i++, suffix );
    }
  while ( stat( n, &s ) == 0 );
  return n;
}


int main( int argc, char *argv[] )
{
  debug_level = 0; /* 1 = warn, 2 = info, 3 = verbose, 4 = debug mode */

  printf( "Bresenham line drawing test.\n" );
  printf( "Press any key to go next test step.\n" );

  printf( "A black screen.\n" );

  if ( visual_init( 800, 600 ) != 0 )
    return -1;

  visual_clear();
  visual_update();
  visual_waitkey();

  color_t c = { 0x00, 0xff, 0xff, 0x00 };
  rect_t  r = { { 0, 0 }, { 200, 200 } };

  printf( "A yellow 200x200 square at ( 0, 0 ).\n" );

  visual_fill( c, r );
  visual_update();
  visual_waitkey();

  surface_t *s = surface_new( 180, 180 );
  coord_t p = { 10, 10 };

  printf( "A black 180x180 square inside the yellow one.\n" );
  visual_display( s, p );
  surface_free( s );
  visual_update();
  visual_waitkey();

  char *fname = find_fname( argv[ 0 ], "bmp" );
  visual_save( fname );
  printf( "Output saved to \"%s\"\n", fname );
  free( fname );

  visual_quit();

  return ask_user_yn( "Everything rendered as expected?" ) != 1;
}
